﻿SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ARITHABORT ON
GO
SET NUMERIC_ROUNDABORT OFF
GO
SET CONCAT_NULL_YIELDS_NULL ON
GO
SET ANSI_PADDING ON
GO
SET ANSI_WARNINGS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[bhp_ApartmentGroupExists]
(
	@Id						INT
)
AS
BEGIN

	SELECT 
		COUNT(*)
	FROM 
		[bht_ApartmentGroup]
	WHERE
		[Id]	= @Id

END
	
GO
CREATE TABLE dbo.bht_Apartment
	(
	Id int NOT NULL IDENTITY (1, 1),
	Name nvarchar(400) NOT NULL,
	NumberOfPeople int NOT NULL,
	Latitude numeric(18, 12) NOT NULL,
	Longitude numeric(18, 12) NOT NULL,
	AreaSize float(53) NOT NULL,
	LocationName nvarchar(400) NOT NULL,
	GroupId int NOT NULL
	)  ON [PRIMARY]
GO
ALTER TABLE dbo.bht_Apartment ADD CONSTRAINT
	PK_bht_Apartment PRIMARY KEY CLUSTERED 
	(
	Id
	) ON [PRIMARY]

GO
ALTER TABLE dbo.bht_Apartment ADD CONSTRAINT
	FK_bht_Apartment_bht_ApartmentGroup FOREIGN KEY
	(
	GroupId
	) REFERENCES dbo.bht_ApartmentGroup
	(
	Id
	) ON UPDATE  NO ACTION 
	 ON DELETE  NO ACTION 
	GO



CREATE PROCEDURE [dbo].[bhp_ApartmentSave]
(
	@Id									INT,
	@Name							NVARCHAR(400),
	@NumberOfPeople		INT,
	@Latitude						NUMERIC(18, 12),
	@Longitude					NUMERIC(18, 12),
	@AreaSize						FLOAT,
	@LocationName			NVARCHAR(400),
	@GroupId						INT
)
AS
BEGIN

	IF @Id = 0 OR NOT EXISTS (SELECT 1 FROM bht_Apartment WHERE Id = @Id)
	BEGIN
		INSERT INTO bht_Apartment (Name, NumberOfPeople, Latitude, Longitude, AreaSize, LocationName, GroupId)
			VALUES (@Name, @NumberOfPeople, @Latitude, @Longitude, @AreaSize, @LocationName, @GroupId)
	END
	ELSE
	BEGIN
		UPDATE
			bht_Apartment
		SET
			Name								= @Name,
			NumberOfPeople			= @NumberOfPeople,
			AreaSize							= @AreaSize,
			Latitude							= @Latitude,
			LocationName				= @LocationName,
			Longitude						= @Longitude,
			GroupId							= @GroupId
		WHERE
			Id										= @Id
	END
	
	SELECT SCOPE_IDENTITY()
END
	
GO